Slice a TupleΒΆ
Slice a Tuple.
# create a tuple
T = (2, 4, 3, 5, 4, 6, 7, 8, 6, 1)
# used tuple[start:stop] the start index is inclusive and the stop index
slice = T[3:5]
# is exclusive
print(_slice) # (5, 4)
# if the start index isn't defined, is taken from the beg inning of the tuple
_slice = T[:6]
print(_slice) # (2, 4, 3, 5, 4, 6)
# if the end index isn't defined, is taken until the end of the tuple
_slice = T[5:]
print(_slice) # (6, 7, 8, 6, 1)
# if neither is defined, returns the full tuple
_slice = T[:]
print(_slice) # (2, 4, 3, 5, 4, 6, 7, 8, 6, 1)
# the indexes can be defined with negative values
_slice = T[-8:-4]
print(_slice) # (3, 5, 4, 6)
# create another tuple
T = tuple("HELLO WORLD")
print(T) # ('H', 'E', 'L', 'L', 'O', ' ', 'W', 'O', 'R', 'L', 'D')
# step specify an increment between the elements to cut of the tuple
#tuple[start:stop:step]
_slice = T[2:9:2]
print(_slice) # ('L', 'O', 'W', 'R')
# returns a tuple with a jump every 3 items
_slice = T[::4]
print(_slice) # ('H', 'O', 'R')
# when step is negative the jump is made back
_slice = T[9:2:-4]
print(_slice) # ('L', ' ')